<template>
  <div>
    <div>
      <el-row v-show="chapterItem.name" :gutter="10" class="mb8">
        <el-col :span="1.5">
          <h4 style="margin: 12px">{{ chapterItem.name }}</h4>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="text"
            style="font-size: 20px"
            icon="el-icon-edit"
            @click="editChapter(chapterKey,'edit')"
          />
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="text"
            style="font-size: 20px"
            icon="el-icon-delete"
            @click="editChapter(chapterKey,'delete')"
          />
        </el-col>
      </el-row>
      <el-table :data="chapterData.children" border>
        <el-table-column label="序号" type="index" />
        <el-table-column
          v-for="(item,index) in chapterTable.columns"
          :key="index"
          :label="item.label"
          :prop="item.prop"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.is_show === 1">
              <el-switch
                v-if="item.prop === 'is_free'"
                v-model="chapterTable.sel[item.prop]"
                :active-value="1"
                :inactive-value="-1"
              />
              <el-input
                v-else-if="item.prop === 'name'"
                v-model="chapterTable.sel[item.prop]"
                placeholder="请输入内容"
              />
            </div>
            <div v-else>
              <span v-if="item.prop === 'is_free'">{{ typeFormat(scope.row.is_free) }}</span>
              <span v-else-if="item.prop === 'exercises'">
                <router-link
                  v-if="scope.row.is_contain_exercise === 1"
                  :to="{name:'subject',
                        params: {
                          id:chapterItem.question_bank_id,
                          chapter_id: scope.row.id,
                          link_type: 2,
                        }}"
                >
                  <span style="color: #1890ff">章节习题</span>
                </router-link>
                <el-button v-else type="text" @click="addExercises(scope.row.id)">添加习题</el-button>
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="editRow(scope.row,scope.$index)">编辑</el-button>
            <el-button :disabled="scope.row.is_show === 0 || scope.row.is_show === -1" type="text" @click="saveRow(scope.row,scope.$index)">保存</el-button>
            <el-button type="text" @click="deleteRow(scope.$index,chapterData.children)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="addsonchapter" @click="addSonchapter()">
        <i class="el-icon-plus" />添加子章节
      </div>
    </div>
    <Exercises :visible="visible" @cancel="cancel" @submitForm="submitForm" />
  </div>
</template>
<script>
import {
  addChapter,
  editChapter,
  delSections,
  chooseExercises
} from '@/api/admin/sys-question'
import Exercises from '@/components/Exercises'
export default {
  components: {
    Exercises
  },
  props: {
    chapterItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    chapterKey: {
      type: Number,
      default: () => {
        return null
      }
    }
  },
  data() {
    return {
      chapterTable: {
        sel: null, // 选中行
        columns: [
          {
            prop: 'name',
            label: '子章节名称'
          },
          {
            prop: 'is_free',
            label: '公开状态'
          },
          {
            prop: 'exercises',
            label: '题目内容'
          }
        ]
      },
      chapterData: {
        children: []
      },
      statusOptions: [
        { label: '已公开', value: 1 },
        { label: '未公开', value: -1 }
      ],
      visible: false,
      loading: true,
      dataList: [],
      total: 0,
      sectionsId: null
    }
  },
  watch: {
    chapterItem: {
      handler(val) {
        this.chapterData = { ...val }
      }
    }
  },
  created() {
    this.chapterData = { ...this.chapterItem }
  },
  methods: {
    // 新增子章节
    addSonchapter() {
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      const j = {
        name: '',
        is_free: -1,
        is_show: 1
      }
      this.chapterData.children.push(j)
      this.chapterTable.sel = JSON.parse(JSON.stringify(j))
    },
    saveRow(row, index) {
      // 保存
      const data = JSON.parse(JSON.stringify(this.chapterTable.sel))
      for (const k in data) {
        row[k] = data[k] // 将sel里面的value赋值给这一行。ps(for....in..)的妙用，细心的同学发现这里我并没有循环对象row
      }
      if (data?.id) {
        editChapter({
          ...data,
          is_show: -1,
          pid: this.chapterData.id,
          question_bank_id: this.chapterData.question_bank_id
        }).then(response => {
          row.is_show = -1
          this.$emit('say', this.chapterData)
        })
        return
      }
      const sections = {
        ...this.chapterData.children[index],
        is_show: -1,
        pid: this.chapterData.id,
        question_bank_id: this.chapterData.question_bank_id
      }
      addChapter(sections).then(res => {
        if (res.code === 200) {
          row.is_show = -1
          this.chapterData.children[index].id = res.data
          this.$emit('say', this.chapterData)
        }
      })
    },
    editRow(row) {
      // 编辑
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      this.chapterTable.sel = row
      row.is_show = 1
      this.$emit('say', this.chapterData)
    },
    deleteRow(index, rows) {
      const deleteData = rows.find((v, i) => i === index)
      if (deleteData.id) {
        this.$confirm('是否确认删除', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delSections({ ids: [deleteData.id], link_id: deleteData.question_bank_id }).then(response => {
              rows.splice(index, 1)
              this.$emit('say', this.chapterData)
            })
          })
          .catch(function() {})
      } else {
        rows.find((v, i) => i === index)
        rows.splice(index, 1)
      }
    },
    editChapter(key, type) {
      const payload = {
        chapterItem: this.chapterData,
        chapterKey: key,
        type
      }
      this.$emit('dialogVisible', payload)
    },
    // 参数系统内置字典翻译
    typeFormat(status) {
      return this.selectDictLabel(this.statusOptions, status)
    },
    addExercises(id) {
      this.visible = true
      this.sectionsId = id
    },
    cancel() {
      this.visible = false
    },

    submitForm(ids) {
      const parmars = {
        link_id: this.chapterItem.question_bank_id,
        chapter_id: this.sectionsId,
        link_type: 2,
        question_bank_str: ids
      }
      chooseExercises(parmars).then(res => {
        this.visible = false
        const { children } = this.chapterData
        const childrens = children.map(item => {
          if (item.id === this.sectionsId) {
            return { ...item, is_contain_exercise: 1 }
          }
          return item
        })
        this.chapterData = {
          ...this.chapterData,
          children: childrens
        }
      })
    }
  }
}
</script>
